package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;

import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(@RequestParam(required = false,defaultValue = "1") Integer page,
                                    @RequestParam(required = false,defaultValue = "10") Integer pageSize,String name){

        Page<Setmeal> setmealPage = new Page<>(page,pageSize);
        //条件查询 并根据修改时间反序
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        setmealWrapper.orderByDesc(Setmeal::getUpdateTime);

        //分页查询出所有套餐信息
        setmealService.page(setmealPage,setmealWrapper);

        //前端还需要菜品信息
        Page<SetmealDto> setmealDtoPage = new Page<>();

        List<SetmealDto> setmealDtos = setmealPage.getRecords().stream().map(
                setmeal -> {
                    SetmealDto setmealDto = new SetmealDto();
                    //将套餐信息封装至dto中
                    BeanUtils.copyProperties(setmeal, setmealDto);

                    //获取该分类名字
                    Category category = categoryService.getById(setmeal.getCategoryId());
                    if (category != null){
                        //将分类名字封装至dto
                        setmealDto.setCategoryName(category.getName());
                    }
                    return setmealDto;
                }
        ).collect(Collectors.toList());

        //组装数据
        setmealDtoPage.setRecords(setmealDtos);
        setmealDtoPage.setTotal(setmealPage.getTotal());

        return R.success(setmealDtoPage);
    }

    /**
     * 添加
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "Setmeal",allEntries = true)
    public R save(@RequestBody SetmealDto setmealDto){

        boolean flag = setmealService.saveWithDish(setmealDto);

        if (!flag){
            return R.error("添加失败，请稍后再试！");
        }
        return R.success();
    }

    /**
     * 根据id回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> selectById(@PathVariable Long id){

        SetmealDto setmealDto = setmealService.selectWithDish(id);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(cacheNames = "Setmeal",allEntries = true)
    public R update(@RequestBody SetmealDto setmealDto){

        boolean flag = setmealService.updateWithDish(setmealDto);

        if (!flag){
            return R.error("修改套餐失败，请稍后再试！");
        }
        return R.success();
    }

    /**
     * 修改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "Setmeal",allEntries = true)
    public R updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){

        setmealService.updateStatusByIds(status,ids);

        return R.success();
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "Setmeal",allEntries = true)
    public R delete(@RequestParam List<Long> ids){
        boolean flag = setmealService.deleteByIds(ids);
        if (!flag){
            return R.error("删除失败，请稍后再试！");
        }
        return R.success();
    }

    /**
     * 获取出售的套餐信息
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(cacheNames = "Setmeal",key ="#a0.id+'_'+#a0.status")
    public R<List<Setmeal>> list( Setmeal setmeal){

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,setmeal.getCategoryId());
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,setmeal.getStatus());

        List<Setmeal> setmeals = setmealService.list(setmealLambdaQueryWrapper);

        return R.success(setmeals);
    }

    /**
     * 客户端套餐详情
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable Long id){

        //首先根据套餐id查询出菜品集合
        LambdaQueryWrapper<SetmealDish> setmealDishWrapper = new LambdaQueryWrapper<>();
        setmealDishWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishService.list(setmealDishWrapper);

        //组合得到dtos
        List<DishDto> dishDtos = setmealDishes.stream().map(
                setmealDish -> {
                    DishDto dishDto = new DishDto();
                    //获取到菜品信息 并组装
                    Dish dish = dishService.getById(setmealDish.getDishId());
                    BeanUtils.copyProperties(dish,dishDto);
                    //组装套餐菜品数量
                    dishDto.setCopies(setmealDish.getCopies());
                    return dishDto;
                }
        ).collect(Collectors.toList());

        return R.success(dishDtos);
    }
}
